package vin.pth.authorization.config;

import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import vin.pth.authorization.filter.AuthorizationFilter;
import vin.pth.authorization.handler.AuthorizationHandler;
import vin.pth.authorization.manager.AuthorizationManager;
import vin.pth.authorization.service.AuthorizationUserService;
import vin.pth.base.pojo.DefaultUserDetails;
import vin.pth.base.service.UserDetailsService;
import vin.pth.core.constant.UsernameConstant;

/**
 * 授权Bean注册器.
 *
 * @author cocoon
 */
@Slf4j
@EnableConfigurationProperties(AuthorizationProperties.class)
@ComponentScan("vin.pth.authorization.*")
@Configuration
@ConditionalOnProperty(name = "cocoon-security.authorization.enable", matchIfMissing = true)
public class AuthorizationBeanRegister {

  @Resource
  private PasswordEncoder passwordEncoder;

  /**
   * 默认的认证用户service.
   *
   * @return AuthorizationUserService
   */
  @ConditionalOnMissingBean(AuthorizationUserService.class)
  @Bean
  public AuthorizationUserService authorizationUserService() {
    return userDetails -> {
      log.warn("默认的token为用户名，请根据业务自行实现!");
      return userDetails.getUsername();
    };
  }

  /**
   * UserDetailsService默认实现.
   *
   * @return UserDetailsService
   */
  @ConditionalOnMissingBean(UserDetailsService.class)
  @Bean
  public UserDetailsService userDetailsService() {
    return username -> {
      log.warn("默认读取默认用户,请根据业务自行实现!");
      if (UsernameConstant.ADMIN.equals(username)) {
        return DefaultUserDetails.adminUser(passwordEncoder.encode(username));
      }
      return DefaultUserDetails.anonymousUser();
    };

  }

  @Bean
  public AuthorizationFilter authorizationFilter(
      AuthorizationManager authorizationManager,
      AuthorizationHandler authorizationHandler) {
    return new AuthorizationFilter(authorizationManager, authorizationHandler);
  }


}
